package com.fuze.controller;

import com.fuze.common.Advice;
import com.fuze.common.CustomException;
import com.fuze.common.Result;
import com.fuze.common.constant.Constant;
import com.fuze.domain.vo.LoginFormVO;
import com.fuze.service.AdministratorsService;
import com.fuze.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author sepc_
 * @date 4/7/2021 15:40
 */
@Api(tags = "授权接口")
@RestController
@RequiredArgsConstructor
@Slf4j
public class AuthController {

    final RedisTemplate<String, Object> redisTemplate;

    final UserService userService;

    final AdministratorsService administratorsService;

    /**
     * 用户登录授权
     *
     * @param loginFormVO 登录表单
     * @return token
     */
    @ApiOperation(value = "用户登录")
    @PostMapping("/auth/login")
    public Result login(@Validated @RequestBody LoginFormVO loginFormVO) {
        String token;
        Integer loginFlag = loginFormVO.getLoginFlag();
        if (loginFlag.equals(Constant.IS_USER)) {
            token = userService.login(loginFormVO);
        } else if (loginFlag.equals(Constant.IS_ADMIN)) {
            token = administratorsService.login(loginFormVO);
        } else {
            throw new CustomException(Advice.LOGON_ID_ERROR);
        }
        return Result.ok(token);
    }

    @ApiOperation(value = "用户登出")
    @GetMapping("/auth/logout")
    public Result logout(HttpServletRequest request) {
        String token = request.getHeader(Constant.AUTH_TOKEN);
        Object o = redisTemplate.opsForValue().get(token);
        if (o == null) {
            throw new CustomException(Advice.FAILED_DELETE_TOKEN);
        }
        redisTemplate.delete(token);
        return Result.ok();
    }

}
